var config = parent.parent.CONFIG,system=parent.parent.SYSTEM;
if(!config){
	config = parent.parent.parent.CONFIG;
	system = parent.parent.parent.SYSTEM;
}
var api = frameElement.api, W = api.opener;
var product = api.data.product || {},sell_type=api.data.sell_type;
var queryUrl = config.BASEPATH+'cash/productSize';
var saveUrl = config.BASEPATH+'cash/saveTemp';
var backUrl = config.BASEPATH+'cash/saveBackTemp';
$.fn.subtext=function(value,count,txt){	
	if (value.length>count){
		if (txt==null){txt='..';}
		$(this).text(value.substring(0,count)+txt);
		$(this).attr('title',value); 
	}else{
		$(this).text(value);
	}    
};
$.fn.subval=function(value,count){	
	if (value.length>count){
		$(this).val(value.substring(0,count));
		$(this).attr('title',value); 
	}else{
		$(this).val(value);
	}    
};
var handle = {
	save:function(){
		var products = paramData.getData();
		if(null == products || products.length == 0){
			W.Public.tips({type: 1, content : "请输入商品数量"});
			return;
		}
		$("#btn-save").prop("disabled",true);
		var _url = saveUrl;
		if(sell_type == 1){
			_url = backUrl;
		}
		$.ajax({
			type:"POST",
			url:_url,
			data:{"sell_type":sell_type,"data":JSON.stringify(products)},
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					W.flag = true;
					paramData.clearData();
					setTimeout("api.close()",200);
				}else{
					W.Public.tips({type: 1, content : data.message});
				}
				$("#btn-save").prop("disabled",false);
			}
		});
	}
};
var THISPAGE = {
	init:function (){
		this.loadGrid();
		this.initEvent();
	},
	buildParam:function(){
		var params = "";
		return params;
	},
	loadGrid:function(){
		$.ajax({
			type:"POST",
			url:queryUrl,
			data:product,
			cache:false,
			dataType:"json",
			success:function(data){
				if(undefined != data && data.stat == 200){
					THISPAGE.initDom(product);
					THISPAGE.initGrid(data.data.columns,data.data.rows);
				}else{
					W.Public.tips({type: 1, content : data.message});
				}
			}
		});
	},
	initDom:function(data){
		this.selectCell={iRow:0,iCol:0,rowid:0,value:''};
		$('#pd_no').text(data.pd_no);
		$('#pd_name').subtext(data.pd_name,10);
		$('#pd_sell_price').text(data.pd_sell_price);
	},
	initGrid:function(columns,datas){
		paramData.clearData();//清空json中临时数据
		var _self = this;
		var colModel = [
	    	{label:'颜色', name: 'cr_name',index: '', width: 80,fixed:true},
	    	{name:'cr_code',hidden:true},
	    	{label:'杯型', name: 'br_name',index: '', width: 50,fixed:true},
	    	{name:'br_code',hidden:true},
	    	{name:'id',hidden:true}
	    ];
		if (columns != null && columns.length > 0){
			for ( var i = 0; i < columns.length; i++) {
				colModel.push({name: columns[i].sz_code,label:columns[i].sz_name, index: columns[i].sz_code, width: 60,editable:true});
			}	
		}
		colModel.push({label:'小计',name:'totalAmount',width:70});
		$('#grid').jqGrid({
			datatype: 'local',
			width:730,
			height:310,
			altRows:true,
			gridview: true,
			onselectrow: false,
			colModel: colModel,
			rownumbers: true,//行号
			viewrecords: true,
			page: 1, //只有一页
			pgbuttons:false,
			pgtext:false,
			shrinkToFit:true,
            cellEdit: true,
            cellsubmit: 'clientArray',
            footerrow: true,
            userDataOnFooter: true,
			jsonReader: {
				root: 'rows',
				repeatitems : false,
				id:'id'
			},
			loadComplete: function(data){
			},
			loadError: function(xhr, status, error){
			},
			formatCell:function (rowid, cellname, value, iRow, iCol){
				var selectCell=_self.selectCell;
				selectCell.rowid=rowid;
				selectCell.iRow=iRow;
				selectCell.iCol=iCol;
				selectCell.value=value;
				var arrValue = value.split('/');
				if (arrValue != ''){
					selectCell.value0 = arrValue[0];
					selectCell.value1 =arrValue[1];
				}else{
					selectCell.value0 = 0;
					selectCell.value1 = '';
				}
				var inputValue = selectCell.value1;
				return inputValue;
			},
			onCellSelect: function(rowid,iCol,cellcontent,e){
			},
			beforeSaveCell :function(rowid, cellname, value, iRow, iCol){
				var selectCell=_self.selectCell;
				var newValue = '';
				if(undefined != value){
					if (Validate.amount(value)){
						if (selectCell.value0 != 0||value != ''){
							newValue = selectCell.value0+'/'+value;	
							paramData.buildData($('#grid').getRowData(rowid),colModel[iCol-1], value);
						}
					}else{
						newValue = _self.selectCell.value;
					}
				}
				return newValue;
			},
			afterSaveCell:function(rowid, cellname, value, iRow, iCol){
				THISPAGE.gridTotal();
			}
	    });
		if (datas != null){
			for(var i=0;i< datas.length;i++){
				$('#grid').jqGrid('addRowData', i + 1, datas[i]);
			}
	    	THISPAGE.reloadGridData(datas);
		}
	},
	reloadGridData:function(datas){
		var grid=$('#grid')
		,rows=grid.getRowData()
		,colModel=grid.getGridParam('colModel');
		for(var rowIndex=0;rowIndex<rows.length;rowIndex++){
			var row = rows[rowIndex];
			for ( var colIndex = 6; colIndex < colModel.length-1; colIndex++) {
				var key= colModel[colIndex].name;
				var arrValue = null;
				var originalValue = null;
				if(row[key] != null && row[key] != ''){
					arrValue = row[key].split('/');
				}
				if(datas[rowIndex][key] != null && datas[rowIndex][key] != ''){
					originalValue = datas[rowIndex][key].split('/');
				}
				var newValue = '';
				if(originalValue != null && originalValue != '' && originalValue.length > 0){
					if(originalValue[0] != null && originalValue[0] != ''){
						newValue += originalValue[0]+'/';
					}
					if(originalValue[1] != null && originalValue[1] != ''){
						newValue += originalValue[1]+'/';	
					}
				}else{
					newValue += '0/';
				}
				
				if (arrValue != null && arrValue != '' && arrValue.length > 0){
					newValue += arrValue[arrValue.length-1];
				}
				rows[rowIndex][key] = newValue;
			}
		}
		grid.clearGridData();
		for(var i=0;i< rows.length;i++){
			grid.jqGrid('addRowData', i + 1, rows[i]);
		}
		THISPAGE.gridTotal();
	},
	gridTotal:function(iRow,iCol){
		var grid = $('#grid')
			,rows = grid.getRowData()
			,colModel = grid.getGridParam('colModel');
		for(var rowIndex=0;rowIndex<rows.length;rowIndex++){
			var total1=0,total2=0;
			var row=rows[rowIndex];
			for ( var colIndex = 6; colIndex < colModel.length-1; colIndex++) {
				var key= colModel[colIndex].name;
				var arrValue=row[key].split('/');
				if (arrValue.length > 0){
					if (arrValue[0] != null && arrValue[0] != '' && !isNaN(arrValue[0])) {
						total1 += parseInt(arrValue[0]);
					}
					if (arrValue[1] != null && arrValue[1] != '' && !isNaN(arrValue[1])) {
						total2 += parseInt(arrValue[1]);
					}				
				}
			}
			grid.setCell(row.id,'totalAmount',total1+"/"+total2);
		}
		rows=grid.getRowData();
		for ( var colIndex = 6; colIndex < colModel.length; colIndex++) {
			var total1 = 0,total2 = 0;
			var key= colModel[colIndex].name;
			for ( var index = 0; index < rows.length; index++) {
	    		var row = rows[index];
				var arrValue = row[key].split('/');
				if (arrValue.length > 0){
					if (arrValue[0] != null && arrValue[0] != '' && !isNaN(arrValue[0])) {
						total1 += parseInt(arrValue[0]);
					}
					if (arrValue[1] != null && arrValue[1] != '' && !isNaN(arrValue[1])) {
						total2 += parseInt(arrValue[1]);
					}				
				}
			}
			json= '{"'+colModel[colIndex].name+'":"'+(total1+'/'+total2)+'"}';
			var jj = eval('('+json+')');
			grid.footerData("set",jj);
		}
		grid.footerData("set",{cr_name:'合计：'});
	},
	initEvent:function(){
		//保存
		$('#btn-save').on('click', function(e){
			handle.save();
		});
		$('#btn_close').on('click', function(e){
			api.close();
		});
	}
};

var paramData={
	datas:[],
	buildData:function(grid,size,amount){
		//保存收银临时表的数据，想一想要不把商品的其他属性全加进来，就不用再查一边商品资料了
		var pdata = $.extend(true,{},product)
		var cr_code = grid.cr_code;
		var br_code = grid.br_code;
		var sz_code = size.name,sz_name = size.label;
		pdata.sht_sub_code=pdata.sht_pd_code+cr_code+sz_code+br_code;
		pdata.sht_cr_code=cr_code;
		pdata.sht_sz_code=sz_code;
		pdata.sht_br_code=br_code;
		pdata.pd_no=product.pd_no;
		pdata.pd_name=product.pd_name;
		pdata.cr_name=grid.cr_name;
		pdata.sz_name=sz_name;
		pdata.br_name=grid.br_name;
		if(sell_type == 1){
			pdata.sht_amount=-Math.abs(amount);
		}else{
			pdata.sht_amount=amount;
		}
		paramData.addData(pdata);
	},
	addData:function(updateData){
		paramData.datas.push(updateData);
	},
	getData:function(){
		var datas = paramData.datas;
		return datas;
	},
	clearData:function(){
		paramData.datas = [];
	}
};

var Validate={
	amount:function(value){
		var reg=/^[0-9]*[0-9][0-9]*$/;
		return reg.test(value);
	}
};

THISPAGE.init();
